#!/bin/bash

# 修复xiaozhi-server systemd服务的脚本
# 解决启动脚本缺失和日志目录问题

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印函数
print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_banner() {
    echo -e "${BLUE}"
    echo "=================================================="
    echo "     XiaoZhi ESP32 Server SystemD 服务修复工具"
    echo "=================================================="
    echo -e "${NC}"
}

# 检查是否在正确的目录
check_directory() {
    if [ ! -f "main/xiaozhi-server/xiaozhi-server.service" ]; then
        print_error "请在xiaozhi-esp32-server项目根目录下运行此脚本"
        exit 1
    fi
    
    print_success "检测到项目目录结构正确"
}

# 获取当前用户和路径信息
get_user_info() {
    CURRENT_USER=$(whoami)
    PROJECT_ROOT=$(pwd)
    XIAOZHI_SERVER_DIR="$PROJECT_ROOT/main/xiaozhi-server"
    
    print_info "当前用户: $CURRENT_USER"
    print_info "项目根目录: $PROJECT_ROOT"
    print_info "服务目录: $XIAOZHI_SERVER_DIR"
}

# 创建日志目录
create_log_directory() {
    print_info "创建日志目录..."
    
    sudo mkdir -p /tmp/xiaozhi-logs
    sudo chown $CURRENT_USER:$CURRENT_USER /tmp/xiaozhi-logs
    sudo chmod 755 /tmp/xiaozhi-logs
    
    print_success "日志目录创建完成: /tmp/xiaozhi-logs"
}

# 创建启动脚本
create_start_script() {
    print_info "检查启动脚本..."
    
    local start_script="$XIAOZHI_SERVER_DIR/start_server.sh"
    
    # 如果文件已存在，检查是否可执行
    if [ -f "$start_script" ]; then
        print_success "启动脚本已存在: $start_script"
        
        # 确保脚本有执行权限
        if [ ! -x "$start_script" ]; then
            print_info "为现有启动脚本添加执行权限..."
            chmod +x "$start_script" || {
                print_error "无法设置启动脚本执行权限"
                return 1
            }
            print_success "启动脚本权限设置完成"
        else
            print_success "启动脚本权限正常"
        fi
        return 0
    fi
    
    print_info "创建新的启动脚本..."
    
    # 确保目录存在且有写入权限
    if [ ! -w "$XIAOZHI_SERVER_DIR" ]; then
        print_error "目录没有写入权限: $XIAOZHI_SERVER_DIR"
        print_info "尝试修复目录权限..."
        chmod 755 "$XIAOZHI_SERVER_DIR" || {
            print_error "无法修复目录权限，请检查文件系统权限"
            return 1
        }
    fi
    
    cat > "$start_script" << 'EOF'
#!/bin/bash

# XiaoZhi ESP32 Server 启动脚本

# 设置工作目录
cd "$(dirname "$0")"

# 激活conda环境（如果存在）
if [ -f "/opt/miniconda3/etc/profile.d/conda.sh" ]; then
    source /opt/miniconda3/etc/profile.d/conda.sh
    conda activate xiaozhi-server 2>/dev/null || echo "Warning: conda environment 'xiaozhi-server' not found"
elif [ -f "$HOME/miniconda3/etc/profile.d/conda.sh" ]; then
    source $HOME/miniconda3/etc/profile.d/conda.sh
    conda activate xiaozhi-server 2>/dev/null || echo "Warning: conda environment 'xiaozhi-server' not found"
elif [ -f "$HOME/anaconda3/etc/profile.d/conda.sh" ]; then
    source $HOME/anaconda3/etc/profile.d/conda.sh
    conda activate xiaozhi-server 2>/dev/null || echo "Warning: conda environment 'xiaozhi-server' not found"
fi

# 设置Python路径
export PYTHONPATH="$PWD:$PYTHONPATH"
export PYTHONUNBUFFERED=1
export PYTHONIOENCODING=utf-8

# 检查配置文件
if [ ! -f "config.yaml" ]; then
    echo "Error: config.yaml not found"
    exit 1
fi

# 启动服务
echo "Starting XiaoZhi ESP32 Server..."
echo "Working directory: $PWD"
echo "Python version: $(python --version 2>&1)"
echo "Starting at: $(date)"

# 启动主程序
exec python app.py
EOF
    
    # 检查文件是否创建成功
    if [ ! -f "$start_script" ]; then
        print_error "启动脚本创建失败: $start_script"
        return 1
    fi
    
    # 设置执行权限
    chmod +x "$start_script" || {
        print_error "无法设置启动脚本执行权限"
        return 1
    }
    
    print_success "启动脚本创建完成: $start_script"
}

# 更新systemd服务文件
update_systemd_service() {
    print_info "更新systemd服务文件..."
    
    local service_file="$XIAOZHI_SERVER_DIR/xiaozhi-server.service"
    local temp_service="/tmp/xiaozhi-server.service"
    
    # 创建更新的服务文件
    cat > "$temp_service" << EOF
[Unit]
Description=XiaoZhi ESP32 Server
Documentation=https://github.com/your-repo/xiaozhi-esp32-server
After=network.target network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$CURRENT_USER
Group=$CURRENT_USER
WorkingDirectory=$XIAOZHI_SERVER_DIR
ExecStart=$XIAOZHI_SERVER_DIR/start_server.sh
ExecReload=/bin/kill -HUP \$MAINPID
KillMode=mixed
KillSignal=SIGINT
TimeoutStopSec=30
Restart=on-failure
RestartSec=10
StartLimitInterval=60
StartLimitBurst=3

# 环境变量
Environment=PATH=/opt/miniconda3/envs/xiaozhi-server/bin:$HOME/miniconda3/envs/xiaozhi-server/bin:$HOME/anaconda3/envs/xiaozhi-server/bin:/usr/local/bin:/usr/bin:/bin
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONIOENCODING=utf-8
Environment=HOME=$HOME

# 日志配置
StandardOutput=append:/tmp/xiaozhi-logs/server.log
StandardError=append:/tmp/xiaozhi-logs/server-error.log
SyslogIdentifier=xiaozhi-server

# 资源限制
#LimitNOFILE=65536
#LimitNPROC=4096
#MemoryLimit=2G
#CPUQuota=200%

# 安全设置（适度放宽以确保正常运行）
NoNewPrivileges=yes
PrivateTmp=no
ProtectSystem=no
ProtectHome=no
ReadWritePaths=$XIAOZHI_SERVER_DIR /tmp/xiaozhi-logs /tmp $HOME
ProtectKernelTunables=no
ProtectKernelModules=no
ProtectControlGroups=no
RestrictRealtime=no
RestrictSUIDSGID=no
RemoveIPC=no

[Install]
WantedBy=multi-user.target
EOF
    
    # 复制到系统目录
    sudo cp "$temp_service" /etc/systemd/system/xiaozhi-server.service
    rm "$temp_service"
    
    print_success "systemd服务文件已更新"
}

# 重新加载并启动服务
reload_and_start_service() {
    print_info "重新加载systemd配置..."
    sudo systemctl daemon-reload
    
    print_info "停止现有服务（如果正在运行）..."
    sudo systemctl stop xiaozhi-server 2>/dev/null || true
    
    print_info "启用服务开机自启..."
    sudo systemctl enable xiaozhi-server
    
    print_info "启动服务..."
    if sudo systemctl start xiaozhi-server; then
        print_success "服务启动成功"
    else
        print_warning "服务启动可能有问题，请检查日志"
    fi
    
    # 等待一下再检查状态
    sleep 3
    
    print_info "检查服务状态..."
    sudo systemctl status xiaozhi-server --no-pager -l
}

# 显示服务管理命令
show_service_commands() {
    echo
    print_info "服务管理命令："
    echo "  查看服务状态: sudo systemctl status xiaozhi-server"
    echo "  启动服务:     sudo systemctl start xiaozhi-server"
    echo "  停止服务:     sudo systemctl stop xiaozhi-server"
    echo "  重启服务:     sudo systemctl restart xiaozhi-server"
    echo "  查看日志:     sudo journalctl -u xiaozhi-server -f"
    echo "  查看错误日志: tail -f /tmp/xiaozhi-logs/server-error.log"
    echo "  查看输出日志: tail -f /tmp/xiaozhi-logs/server.log"
}

# 检查依赖
check_dependencies() {
    print_info "检查Python环境..."
    
    cd "$XIAOZHI_SERVER_DIR"
    
    # 检查app.py是否存在
    if [ ! -f "app.py" ]; then
        print_error "app.py 文件不存在，请确保在正确的目录"
        return 1
    fi
    
    # 检查config.yaml是否存在
    if [ ! -f "config.yaml" ]; then
        print_warning "config.yaml 不存在，服务可能无法正常启动"
        print_info "请确保配置文件存在或从config_from_api.yaml复制"
    fi
    
    # 检查requirements.txt
    if [ -f "requirements.txt" ]; then
        print_info "发现requirements.txt，建议确保所有依赖已安装"
        print_info "可以运行: pip install -r requirements.txt"
    fi
    
    print_success "基本文件检查完成"
}

# 主函数
main() {
    print_banner
    
    # 检查是否为root用户
    if [ "$EUID" -eq 0 ]; then
        print_error "请不要使用root用户运行此脚本"
        print_info "建议使用普通用户运行，脚本会在需要时自动使用sudo"
        exit 1
    fi
    
    # 执行修复步骤
    check_directory
    get_user_info
    create_log_directory
    create_start_script
    check_dependencies
    update_systemd_service
    reload_and_start_service
    show_service_commands
    
    print_success "SystemD服务修复完成！"
}

# 运行主函数
main "$@"